/**
 * Created by ziyu on 17/3/9.
 */

import React, {Component, PropTypes} from 'react'
import {Form, Input, Button, Progress, message} from 'antd'
import {exportFile, fetchPost} from '../../../../utils/request'
import Styles from '../../less/DlButton.less'
import moment from 'moment'
import XLSX from 'xlsx';

class DlButton extends React.Component {
  /**
   * 服务端代码只需要提供查询接口，数据组装由js完成，所以理论上不会引发后台服务崩溃
   * 查询每次查10000条，如果有多页，会触发多次查询，前端组装数据
   *
   * downloadUrl: 下载接口地址，必须支持分页查询，必传参数
   * downloadParams: 查询用，json格式，即api接口入参，必传参数
   * fileName: 文件名,可选参数
   *
   * 返回数据要求: code、msg、data、page, 其中data.itemList是二维数据 即arrayList的每个成员也是array
   * 返回数据示例:
   {
    "code": 0,
    "msg": "SUCCESS",
    "data": {
        "itemList": [
            [
                "Product",
                "Loan ID",
                "Collection No",
                "Mobile",
                "Name",
                "Last call",
                "Agent Name",
                "Admin ID",
                "Planned Repayment Date",
                "Borrow Capital",
                "Total Amount Should Repay",
                "Actual Repayment Time",
                "Repaid Amount"
            ],
            [
                "CASHMAMA",
                "171695764022620477TD",
                "200208ADCT0631494611",
                "9370055744",
                "SWAPNIL PATIL",
                "2020-02-08 09:43:23",
                "Uday",
                "40228",
                "2020-02-08 00:00:00",
                "5000.00",
                "5067.00",
                "",
                "0.00"
            ],
            [
                "BEAUTYCASH",
                "171699091548417341TD",
                "200208ADCT0631518700",
                "9849539500",
                "KUUNTUMALLA sree manjula",
                "2020-02-08 09:43:44",
                "Karthik",
                "40250",
                "2020-02-08 00:00:00",
                "3000.00",
                "3040.00",
                "",
                "0.00"
            ],
            [
                "CASHBULL",
                "171708733750064445TD",
                "200208ADCT0631689400",
                "8118849636",
                "Pawan Sharma",
                "2020-02-08 10:33:14",
                "Sairam",
                "40172",
                "2020-02-08 00:00:00",
                "3000.00",
                "3040.00",
                "",
                "0.00"
            ]
        ]
    },
    "page": {
        "pageSize": 10000,
        "currentPage": 1,
        "totalCount": 3,
        "startIndex": 0,
        "endIndex": 10000,
        "totalPage": 1,
        "sortType": 0,
        "firstPage": true,
        "totalPageNum": 1
    }
  }
   */

  constructor(props) {
    super(props)
    this.state = {
      progressShow: false, //进度条
      percent: 0,
      progressStatus: null,
      downloadUrl: props.downloadUrl,
      buttonName: props.buttonName?props.buttonName:'Export',
      fileName: props.fileName,
      params: props.downloadParams,
    }

  }

  componentDidMount() {
  }

  componentWillReceiveProps(props) {
    if (this.state.params !== props.downloadParams) {
      this.setState({
        params: props.downloadParams
      })
    }
  }

  componentWillMount() {

  }

  // 导出excel
  handelExport = async () => {
    let fileName = this.state.fileName ? this.state.fileName : `data-${moment().format('YYYY-MM-DD HH-mm-ss')}.xlsx`
    this.setState({
      buttonHidden: true,
      progressShow: true,
      progressStatus: 'active',
    })

    let currentPage = 1
    let pageSize = 10000
    let copyParams = {}
    if (typeof this.state.params == 'undefined' || this.state.params == null) {
      copyParams = {}
    } else {
      //去除为空参数
      for (let i in this.state.params) {
        if (this.state.params[i] && this.state.params[i] !== '') {
          copyParams[i] = this.state.params[i]
        }
      }
    }
    let newList = []
    let json = await fetchPost(`${this.state.downloadUrl}?currentPage=${currentPage}&pageSize=${pageSize}`, copyParams)
    let page = json.page
    if (json.code === 0 && page && json.data && json.data.itemList && json.data.itemList.length > 0) {
      newList.push.apply(newList, json.data.itemList);
      this.setState({
        percent: Math.round(page.currentPage * 100 / page.totalPageNum)
      })
    } else {
      this.setState({
        buttonHidden: false,
        progressStatus: 'exception',
      }, () => {
        message.error('No Data!')
      })
      return
    }

    //如果有多页，继续从第二页开始查
    if (page && page.totalPageNum) {
      for (let i = 2; i <= page.totalPageNum; i++) {
        let jsonTmp = await fetchPost(`${this.state.downloadUrl}?currentPage=${i}&pageSize=${pageSize}`, copyParams)
        if (jsonTmp.code === 0 && jsonTmp.data && jsonTmp.data.itemList) {
          jsonTmp.data.itemList.splice(0, 1);
          newList.push.apply(newList, jsonTmp.data.itemList);
          this.setState({
            percent: Math.round(i * 100 / page.totalPageNum)
          })
        }
      }
    }
    await this.exportExcel(newList, fileName);

    this.setState({
      buttonHidden: false,
      progressStatus: 'success',
    })
  }

// 将一个sheet转成最终的excel文件的blob对象，然后利用URL.createObjectURL下载
  sheet2blob(sheet, sheetName) {
    sheetName = sheetName || 'sheet1';
    var workbook = {
      SheetNames: [sheetName],
      Sheets: {}
    };
    workbook.Sheets[sheetName] = sheet;
    // 生成excel的配置项
    var wopts = {
      bookType: 'xlsx', // 要生成的文件类型
      bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
      type: 'binary'
    };
    var wbout = XLSX.write(workbook, wopts);
    var blob = new Blob([s2ab(wbout)], {type: "application/octet-stream"});

    // 字符串转ArrayBuffer
    function s2ab(s) {
      var buf = new ArrayBuffer(s.length);
      var view = new Uint8Array(buf);
      for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
      return buf;
    }

    return blob;
  }

  /**
   * 通用的打开下载对话框方法，没有测试过具体兼容性
   * @param url 下载地址，也可以是一个blob对象，必选
   * @param saveName 保存文件名，可选
   */
  openDownloadDialog(url, saveName) {
    if (typeof url == 'object' && url instanceof Blob) {
      url = URL.createObjectURL(url); // 创建blob地址
    }
    var aLink = document.createElement('a');
    aLink.href = url;
    aLink.download = saveName || ''; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
    var event;
    if (window.MouseEvent) event = new MouseEvent('click');
    else {
      event = document.createEvent('MouseEvents');
      event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    }
    aLink.dispatchEvent(event);
  }

  // 传入jsonArray 执行后就会弹出下载框
  exportExcel(arrayOfArrays, fileName) {
    var sheet = XLSX.utils.aoa_to_sheet(arrayOfArrays)
    var blob = this.sheet2blob(sheet)
    this.openDownloadDialog(blob, fileName ? fileName : 'data.xlsx')
  }

  render() {
    return (
      <span>
        <Button icon='download' type='primary' disabled={this.state.buttonHidden}
                onClick={this.handelExport}>{this.state.buttonName}</Button>
        {
          this.state.progressShow ?
            <Progress className={Styles.progressLeft} type="circle" percent={this.state.percent} width={28}
                      status={this.state.progressStatus}/> : null
        }
      </span>
    )
  }
}

DlButton = Form.create()(DlButton)
export default DlButton
